﻿
Windows.Graphics.Display.DisplayInformation.autoRotationPreferences = Windows.Graphics.Display.DisplayOrientations.landscape | Windows.Graphics.Display.DisplayOrientations.portraitFlipped;
var appConfig = {
    //BaseUrl: "http://172.16.5.140/release/AccNete",
    //BaseUrl: "http://accnet.cloud.com.vn:8080",
    BaseUrl: "http://localhost:9254",
    session: "winrt",
    schema: "dbo",
}

var WS = {
    $AuthentificationToken: "public",
    $setUrl: function (url) {
       
        ngW8.$("$store").$set("$SERVICE_URL",url);
     
    },
    $getUrl: function (AsmName, ObjectType, Method) {
        if (!ngW8.$("$store").$get("$SERVICE_URL")) {
            return undefined;
        }
        return ngW8.$("$store").$get("$SERVICE_URL")+"/api/";
    },
    $showErrorInFrame:function(errorText){
        var div = $("<div><iframe></iframe></div>").appendTo("body");
        div.kendoWindow({
            width: $(window).width() - 40,
            height: $(window).height() - 40
        });
        div.data("kendoWindow").center()
        var iframe = div.children()[0];
        $(iframe).css("width", $(window).width() - 40);
        $(iframe).css("height", $(window).height() - 60);

        var safeData = window.toStaticHTML(errorText);
        iframe.contentWindow.document.open();
        iframe.contentWindow.document.write(safeData);
        iframe.contentWindow.document.close();
    },
    $call: function (ControllerActions, Params, callback, errorCallback) {
        var me = this;
        if (angular.isUndefined(me.$getUrl())) {
            if (callback) {
                callback();
            }
            return;
        }

        $.ajax({
            type: "POST",
            url: me.$getUrl() + ControllerActions,
            data: JSON.stringify(Params),
            success: function (res) {
                if (res.IsError) {
                    if (res.Exception) {
                        me.$showErrorInFrame(res.Message);
                        return;
                    }
                }
                callback(res);

            },
            error: function (error) {
                if (errorCallback) {
                    if (errorCallback()) {
                        return;
                    }
                }
                var cancel = false;
                if (window.top.$onCallWebServiceErrorHandler) {
                    cancel = window.top.$onCallWebServiceErrorHandler({
                        url: $(this)[0].url,
                        error: error
                    });
                }
                if (cancel) return;
                me.$showErrorInFrame(error.responseText);
                errorCallback(error);
            },
            processData: true,
            dataType: "json",
            contentType: "application/json; charset=utf-8"
        });

    }
};
kendo.culture("vi-VN");

$(window).load(function () {
    document.addEventListener("focus", function (event) {
        setTimeout(function () {
            //if (typeof event.target.select != "undefined")
              // event.target.select();
        });

    }, true);
});


function ReloadGridData(gridViewName) {
    var grid = $('#' + gridViewName).data("kendoGrid");;
    grid.dataSource.read();
}

function GetCurrentRowEx(gridView) {
    var selectedRow = gridView.select();

    if (selectedRow != null) {
        var data = gridView.dataItem(selectedRow);

        return data;
    }
    else
        return null;
}

function GetCurrentRow(gridViewName) {

    var gridView = $('#' + gridViewName).data("kendoGrid");

    var selectedRow = gridView.select();

    if (selectedRow != null) {
        var data = gridView.dataItem(selectedRow);
        if(typeof data != "undefined")
            return data;
        return null;
    }
    else
        return null;
}

function ResizeGrid(gridViewName) {
    if (typeof IsModernUI != 'undefined' && IsModernUI == true)
    {
        SetHeightGrid(gridViewName, $(window).height() - $("#top").height() - $("#title").height()-45);
    }
    else
    {
        SetHeightGrid(gridViewName, $(window).height() - 43);
    }
}

function SetHeightGrid(gridViewName,height)
{
    var gridElement = $("#" + gridViewName);

    gridElement.height(height);

    var dataArea = gridElement.find(".k-grid-content");
    var gridHeight = gridElement.innerHeight();
    var otherElements = gridElement.children().not(".k-grid-content").not(".k-grid-content-locked");
    var otherElementsHeight = 0;

    otherElements.each(function () {
        otherElementsHeight += $(this).outerHeight();
    });

    dataArea.height(gridHeight - otherElementsHeight);
}


function FixHeightGrid(gridViewName) {
    var gridElement = $("#" + gridViewName);

    var dataArea = gridElement.find(".k-grid-content");
    var gridHeight = gridElement.innerHeight();
    var otherElements = gridElement.children().not(".k-grid-content").not(".k-grid-content-locked");
    var otherElementsHeight = 0;

    otherElements.each(function () {
        otherElementsHeight += $(this).outerHeight();
    });

    dataArea.height(gridHeight - otherElementsHeight);
}


function OpenForm(url, width, height, displayMode, title, modal, name) {

    ShowWindow(url, width, height, displayMode, title, modal, name);
}


$.extend({
    getUrlVars: function () {
        var vars = [], hash;

        var lib = new libAccNetC.lib();


        var hashes = lib.queryPara.split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },

    getStringVar: function (_string,key) {
        var vars = [], hash;

        var hashes;

        if(_string.indexOf('?')>0)
            hashes = _string.slice(_string.indexOf('?') + 1).split('&');
        else
            hashes = _string.slice(_string).split('&');

        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            if (hash[0] == key) return hash[1];
            
        }
        return "";
    },

    
    ModifiedParaUrl: function (url, key, value) {
        var urlNew, hash;

        urlNew = url.substring(0, url.indexOf('?') + 1);
        var hashes = url.slice(url.indexOf('?') + 1).split('&');

        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            if (i != 0) urlNew = urlNew + "&";
            if (hash[0] == key) {
                urlNew = urlNew + hash[0] + "=" + value;
            }
            else {
                urlNew = urlNew + hash[0] + "=" + hash[1];
            }
            
        }
        return urlNew;
    },

    getUrlVar: function (name) {
        var lib = new libAccNetC.lib();

        if(name.toLowerCase() == "copy" && name.toLowerCase() ==lib.actionForm.toLowerCase())
        {
            return "1";
        }
        return $.getUrlVars()[name];
    },

    removeParameter: function (url, parameter)
    {
        var fragment = url.split('#');
        var urlparts= fragment[0].split('?');

        if (urlparts.length>=2)
        {
            var urlBase=urlparts.shift(); //get first part, and remove from array
            var queryString=urlparts.join("?"); //join it back up

            var prefix = encodeURIComponent(parameter)+'=';
            var pars = queryString.split(/[&;]/g);
            for (var i= pars.length; i-->0;) {               //reverse iteration as may be destructive
                if (pars[i].lastIndexOf(prefix, 0)!==-1) {   //idiom for string.startsWith
                    pars.splice(i, 1);
                }
            }
            url = urlBase+'?'+pars.join('&');
            if (fragment[1]) {
                url += "#" + fragment[1];
            }
        }
        return url;
    }
});

(function ($) {
    $.fn.serializeDisabled = function () {
        var obj = {};

        $(':disabled[name]', this).each(function () {
            obj[this.name] = $(this).val();
        });
        return $.param(obj);
    }

    $.fn.serializeCustom = function () {
        var obj = {};

        $(':input', this).each(function () {
            if (this.id != "")
                if (this.type == "checkbox")
                    if($(this).attr('checked')=='checked')
                        obj[this.id] = true;
                    else
                        obj[this.id] = false;
                else
                    obj[this.id] = $(this).val();
        });
        return $.param(obj);
    }
})(jQuery);


function PostModel(url, model, callback) {
    if (Windows.Storage.ApplicationData.current.localSettings.values.hasKey("session"))
        appConfig.session = Windows.Storage.ApplicationData.current.localSettings.values["session"];
    

    request = $.ajax({
        headers: { 'winrt': appConfig.session },
        type: "POST",
        url: url,
        data: JSON.stringify(model),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: callback,

    });


    request.fail(function (jqXHR, textStatus) {
        lvlog(textStatus, "custom", "customType");
        lvlog(jqXHR.responseText, "custom", "customType");
    });
}

function PostServer(url, dataPost) {
    if (Windows.Storage.ApplicationData.current.localSettings.values.hasKey("session"))
        appConfig.session = Windows.Storage.ApplicationData.current.localSettings.values["session"];


    var data = null;
    var r = null;
    if (IsNullOrEmty(dataPost)) {
        r = $.ajax({
            headers: { 'winrt': appConfig.session },
            url: url,
            crossDomain: true,
            dataType: "json",
            async: false,
            cache: false
        });
    }
    else {
        r = $.ajax({
            headers: { 'winrt': appConfig.session },
            url: url,
            crossDomain: true,
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            type: "POST",
            data: dataPost,
            async: false,
            cache: false
        });
    }

    lvlog(r.responseText, "custom", "customType");
    if (r.responseText == null || r.responseText == "")
        return null;
    try {
        data = $.parseJSON(r.responseText)
    }
    catch (err) {
        
        data = null;
    }

    
    return data;
}

function ShowControl(name) {
    document.getElementById(name).style.display = "block";
}

function HideControl(name) {
    document.getElementById(name).style.display = "none";
}

function isString(o) {
    return typeof o == "string" || (typeof o == "object" && o.constructor === String);
}

function SelectRowByCondition(gridView, condition) {
    var data = gridView.dataSource.data();

    var i = 0;
    for (i = 0; i < data.length; i++) {
        var dataItem = data[i];
        // use the dataItem
        if (condition(dataItem))
            break;
    }

    SelectRowByIndex(gridView, i);
}

function SelectRowByIndex(gridView, index) {
    var grid = null;
    if (isString(gridView)) {
        grid = $("#" + gridView).data("kendoGrid");
    }
    else {
        grid = gridView;
    }
    var row = grid.tbody.find(">tr:not(.k-grouping-row)").eq(index);
    if (index == -1)
        SelectFirstRow(grid);
    else
        gridView.select(row);
}

function SelectFirstRow(gridView) {
    gridView.select(gridView.tbody.find(">tr:first"));
}

function SelectLastRow(gridView) {
    SelectRowByIndex(gridView, gridView.dataSource.data().length - 1);
}

function ShowBusy(name) {
    $('#' + name).show();
}

function HideBusy(name) {
    $('#' + name).hide();
}

function GetColumnHeader(GridName, ColumnName) {
    var gridview = $('#' + GridName).data("kendoGrid");
    var title = "";
    $(gridview.columns).each(function (i, e) {
        if (e.field == ColumnName) {
            title = $(e.title)[0].innerHTML;
        }
    });
    return title;
}

function menuColumnAction(obj, ObjParent, ParaEx) {
    if (ObjParent != null) {
        if (this.data.alias == "HideCol") {

            $(ObjParent.columns).each(function (i, e) {
                if (obj.id === 'col' + e.field) {
                    ObjParent.hideColumn(i);
                    return;
                }
            });
        }
        else if (this.data.alias == "SavePri" || this.data.alias == "SavePul") {
            var dataGVS = "[";

            $(ObjParent.columns).each(function (i, e) {
                if (i != 0)
                    dataGVS = dataGVS + ",";
                dataGVS = dataGVS + "{";


                dataGVS = dataGVS + "\"GridViewName\":\"" + ObjParent.wrapper[0].id + "\",";
                dataGVS = dataGVS + "\"FormName\":\"" + ParaEx + "\",";
                dataGVS = dataGVS + "\"FieldName\":\"" + e.field + "\",";
                if (typeof e.width == "number")
                    dataGVS = dataGVS + "\"Width\":" + e.width + ",";
                else
                    dataGVS = dataGVS + "\"Width\":" + e.width.replace('px', '') + ",";

                if (e.hidden && e.hidden == true)
                    dataGVS = dataGVS + "\"IsVisible\":" + "false";
                else
                    dataGVS = dataGVS + "\"IsVisible\":" + "true";
                dataGVS = dataGVS + "}";
            });
            dataGVS = dataGVS + "]";
            $.ajax({
                type: "POST",
                url: GetBaseUrl() + "LVGridView/SaveGrid",
                data: dataGVS,
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (e) {
                    if (e == true) {
                        var win = ShowMessage('AccNet i', 'SaveCompleted', 'Save Completed.', null, null, 'OK');
                    }
                }
            });
        }

    }
}


function SaveAddRefresh() {
    if (typeof _codeBaseGrid != 'undefined') {
        _codeBaseGrid.SaveAddRefresh();
    }
}

/**
 * ReplaceAll by Fagner Brack (MIT Licensed)
 * Replaces all occurrences of a substring in a string
 */
String.prototype.replaceAll = function (token, newToken, ignoreCase) {
    var _token;
    var str = this + "";
    var i = -1;

    if (typeof token === "string") {

        if (ignoreCase) {

            _token = token.toLowerCase();

            while ((
                i = str.toLowerCase().indexOf(
                    token, i >= 0 ? i + newToken.length : 0
                )) !== -1
            ) {
                str = str.substring(0, i) +
                    newToken +
                    str.substring(i + token.length);
            }

        } else {
            return this.split(token).join(newToken);
        }

    }
    return str;
};

function formatNumber(number, format) {
    if (number == null || number == "")
        number = 0;
    format = format.replaceAll("@", "#");
    return kendo.toString(number, format);
}

function formatData(date, format) {
    if (date == null || date == "")
        return null;
    return kendo.toString(toDate(date), format);
}

function toDate(value) {

    var dateRegExp = /^\/Date\((.*?)\)\/$/;

    var date = dateRegExp.exec(value);

    return new Date(parseInt(date[1]));

}

function ShowMessageErrorLevel1(code, defaultMessage, callback, para1) {
    ShowMessageError(code, defaultMessage, callback, para1);
}

function disableControl(name) {
    if (document.getElementById(name) != null)
        document.getElementById(name).disabled = true;
}

function enableControl(name) {
    if (document.getElementById(name) != null)
        document.getElementById(name).disabled = false;
}

function GetBaseUrl() {
    return appConfig.BaseUrl + '/';
}

function attachTextListener(input, func) {
    if (window.addEventListener) {
        input.addEventListener('input', func, false);
    } else
        input.attachEvent('onpropertychange', function () {
            func.call(input);
        });
}

function summarygrid(gridName, field, type, format) {
    var gridview = $('#' + gridName).data("kendoGrid");

    var sum = 0;

    gridview.dataSource.data().forEach(function (e) {
        sum = sum + e[field];
    });

    return formatNumber(sum, format);
}

function CheckComboInList() {
    if (this.value() && this.selectedIndex == -1) {
        var combobox = $("#" + $(this)[0].element.context.id + "").data("kendoComboBox");
        if (typeof combobox != "undefined" && combobox != null) {
            combobox.value(null);
        }
        if (typeof _codeBaseGrid != "undefined")
            _codeBaseGrid.SetValue($(this)[0].element.context.id, null, true);
        if (typeof codeBasePopup != "undefined" && objControls!=null)
            codeBasePopup.SetValue($(this)[0].element.context.id, null, true);
       
        //var win = ShowMessage('AccNet i', 'ItemInList', 'Do you choose item in list.', SetFocusComboNotInList, null, 'OK');
        $(this).focus();
        //win.ControlAssign = this;
    }

}

function SetFocusComboNotInList(combo) {
    if (this.ControlAssign != null) {
        $(this.ControlAssign).focus();
        this.ControlAssign = null;
    }
}

kendo.ui.DatePicker.prototype.focus = function () {
    var that = this, element = that.element;

    that.dateView.toggle();

    if (element[0] !== document.activeElement) {
        element.focus();
    }
}

kendo.ui.Grid.prototype.urlOld = null;
kendo.ui.Grid.prototype.OldDataSelect = null;
kendo.ui.Grid.prototype.OldRowSelect = null;
kendo.ui.Grid.prototype.IsValidate = false;
kendo.ui.Grid.prototype.IsRowChanged = false;
kendo.ui.Grid.prototype.ReSelect = function () {
    var that = this;
    that.IsReSelect = true;
    that.select(that.OldRowSelect);
}


kendo.ui.Grid.prototype.ColumnIsReadOnly = function (columnName,readOnly)
{
    var that = this;
    var c = null;
    for (var i = 0; i < that.columns.length; i++) {
        if (that.columns[i].field == columnName) {
            c = that.columns[i];
            break;
        }
    }

    if (c == null)
        return true;

    if (typeof readOnly == "undefined")
    {
        return c.editable == "undefined" ? false : !c.editable;
    }
    else
    {
        c.editable = !readOnly;
    }
}

function getLabel(name) {
    if ($('#' + name).length>0)
        return $('#' + name)[0].innerHTML;
    return name;
}


function setLabel(name, value) {
    $('#' + name)[0].innerHTML = value;
}


function initSearchGrid() {
    if ($(".searchGrid").length != 0) {
        $($(".searchGrid")[0]).keydown(function (e) {
            if (e.keyCode == 13) {
                var gridview = $('#' + this.title).data("kendoGrid");
                var _url = gridview.dataSource.options.transport.read.url;

                if (_url.indexOf("fieldcustomPredicate") < 0) {
                    _url = _url + "&fieldcustomPredicate=&valuecustomPredicate="
                }

                if (_url.indexOf("searchgrid") > 0) {
                    _url = _url.substring(0, _url.indexOf("searchgrid") - 1);
                }
                gridview.dataSource.transport.options.read.url = _url + '&searchgrid=' + encodeURI($(this).val

());
                gridview.dataSource.page(0);
                e.preventDefault();
            }
        })
    }
}

function onSelectMenuFunction(id) {
    MoreFunctionClick(id);
}

function ShowLanguage()
{
    var base = GetBaseUrl();
    var url = document.location.href;
    url = url.replace(base, '');
    var i = url.indexOf('/');

    if(i==-1)
        i = url.indexOf('?');

    if (i != -1) {
        url = url.substring(0, i);
    }
    
    url = base + url + '/ShowLanguage';
    ShowWindowCallback(url, 600, 550, "Show Language", function (result) { if (result == 1) document.location.reload(true); }, 1, "");
}

function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function Guid() {
    guid = (S4() + S4() + "-" + S4() + "-4" + S4().substr(0, 3) + "-" + S4() + "-" + S4() + S4() + S4

()).toLowerCase();
    return guid;
}

function GenarateIDWindow() {
    name = 'w' + (S4() + S4() + S4() + "-4" + S4().substr(0, 3) + S4() + S4() + S4() + S4()).toLowerCase

();
    return name;
}

function ShowWindow(url, width, height, displayMode, title, modal, name) {
    if (window.frameElement == null)
        return _showWindow(url, width, height, displayMode, title, null, modal, name);
    else
        return window.parent._showWindow(url, width, height, displayMode, title, null, modal, name);
}


function ShowWindowCallback(url, width, height, title, callback, modal, name) {
    var nav = document.body.querySelector('#createNavBar');
    if (!IsNullOrEmty(nav))
        nav.winControl.hide();

    var appbar = document.body.querySelector('#commandsAppBar');
    if (!IsNullOrEmty(appbar))
        appbar.winControl.hide();

    var flyout = document.getElementById("confirmFlyout")
    var renderHost = flyout.querySelector("#flyoutcontent");

    

    url = url.replace(GetBaseUrl(), "").split("?");

    var lib = new libAccNetC.lib();
    var path = lib.checkExistPage(url[0] + ".html");

    if (url.length > 1) {
        lib.queryPopup = url[1];
        lib.queryPopup = lib.queryPopup + "&wintitle=" + title;
    }
    if (path == "")
    {
        WinRT_ShowMessage("This function is processing and will have in next version.");
        return;
    }
    renderHost.children[0].src = path;
    $(flyout).css("width", width + 100);
    $(flyout).css("max-width", width + 100);
    $(flyout).css("height", height + 100);
    $(flyout).css("max-height", height + 100);

    flyout.winControl.callback = callback;

    if($(".header").length>0)
        flyout.winControl.show($(".header")[0], "bottom");
    else{
        flyout.winControl.show($("body")[0], "top","center");
    }

    ////WinJS.UI.Pages.render(path, renderHost).done(function ()
    ////{
    ////    flyout.winControl.show($(".header")[0], "bottom");
    ////});

    
}


function ShowMessage(title, code, defaultMessage, callback, para1, button) {
    var message = [];
    if (!IsNullOrEmty(code)) {
        message = PostServer(appConfig.BaseUrl + "/Shared/WinRT_GetMessage?code=" + code);
    }
    else {
        message.CustomName = defaultMessage;

    }

    var m = message.CustomName;
    if (!IsNullOrEmty(para1))
        m=m.format(para1);
    WinRT_ShowMessage(m, button, callback);
}


function ShowMessageError(code, defaultMessage, callback, para1, button) {
    var message =[];
    if(!IsNullOrEmty(code))
    {
        message= PostServer(appConfig.BaseUrl + "/Shared/WinRT_GetMessage?code=" + code);
    }
    else
    {
        message.CustomName = defaultMessage;

    }
    var m = message.CustomName;
    if(!IsNullOrEmty( para1))
        m= m.format(para1);
    WinRT_ShowMessage(m, button, callback);
}

String.prototype.format = String.prototype.f = function () {
    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};

// Array Remove - By John Resig (MIT Licensed)
function RemoveItemArray(array, from, to) {
    if (from >= array.length) return;
    var rest = array.slice((to || from) + 1 || array.length);
    array.length = from < 0 ? array.length + from : from;
    return array.push.apply(array, rest);
}

function GetCurrentModelCombo(comboName) {
    var combobox = $("#" + comboName).data("kendoComboBox");
    if (combobox) {
        var model = combobox.dataSource.data()[combobox.select()];
        return model;
    }
    return null;
}

function GetCurrentModelLVCombo(comboName) {
    var combobox = $("#" + comboName).LVComboBox().data("LVComboBox");
    if (combobox) {
        var model = combobox.CurentModel();
        return model;
    }
    return null;
}

function SetValueForGrid(gridName, field, value) {
    var gridview = $("#" + gridName).data("kendoGrid");

    var item = GetCurrentRowEx(gridview);

    if (typeof item != 'undefined') {
            item.set(field, value);
    }
}

function GetValueForGrid(gridName, field) {
    var gridview = $("#" + gridName).data("kendoGrid");

    var item = GetCurrentRowEx(gridview);

    if (typeof item != 'undefined') {
        if (item[field] != '"[object Object]"')
            return item[field];
    }
    return null;
}

function GetDate(fieldName) {
    var datePicker = $("#" + fieldName + "").data("kendoDatePicker");
    return datePicker.value();
}

function GetDateEx(fieldName) {
    var v = GetDate(fieldName);
    if (!IsNullOrEmty(v))
        return kendo.toString(v, 'dd/MM/yyyy');
    return null;
}


function GetNumber(fieldName) {
    var numerictextbox = $("#" + fieldName + "").data("kendoNumericTextBox");
    // bind to the change event
    return numerictextbox.value();
}

function GetCombobox(fieldName) {
    var combobox = $("#" + fieldName + "").data("kendoComboBox");
    return combobox.value();
}


function GetLVCombobox(fieldName) {
    var combobox = $("#" + fieldName + "").LVComboBox().data("LVComboBox");
    return combobox.value();
}

function SetDate(fieldName, value) {
    var datePicker = $("#" + fieldName + "").data("kendoDatePicker");
    return datePicker.value(value);
}

function SetNumber(fieldName, value) {
    var numerictextbox = $("#" + fieldName + "").data("kendoNumericTextBox");
    // bind to the change event
    return numerictextbox.value(value);
}

function SetCombobox(fieldName, value) {
    var combobox = $("#" + fieldName + "").data("kendoComboBox");
    return combobox.value(value);
}


function SetLVCombobox(fieldName,value,text) {
    var combobox = $("#" + fieldName + "").LVComboBox().data("LVComboBox");
    return combobox.value(value, text);
}

function IsNull(obj)
{
    if (typeof obj == 'undefined' || obj == null)
        return true;
    return false;
}


function IsNullOrEmty(obj) {
    return IsNull(obj) || obj == "";
}

function RepNullOrEmpty(obj,TrueValue,FalseValue) {
    if (IsNullOrEmty(obj))
        return TrueValue;
    else
        if (IsNull(FalseValue))
            return obj;
        else
            return FalseValue;
}


function PrintReport(Module, dataSet, ReportName, Title, storeName, para) {
    var url = GetBaseUrl() + "ReportViewer.aspx?Module=" + Module + "&EntityName=" + dataSet + "&ReportName=" + ReportName + "&FormTitle=" + Title + "&StoreProcedure=" + storeName + '&' + para;

    WinRT_ShowReport(url);
};


function PrintReportFromView(Module, dataSet, ReportName, Title, ViewName, para) {
    var url = GetBaseUrl() + "ReportViewer.aspx?Module=" + Module + "&EntityName=" + dataSet + "&ReportName=" + ReportName + "&FormTitle=" + Title + "&ViewName=" + ViewName + '&' + para;

    WinRT_ShowReport(url);
};

function SetPredicateForCombo (fieldName, fieldsource, value) {
    var combobox = $("#" + fieldName + "").data("kendoComboBox");
        combobox.dataSource.filter({ field: fieldsource, operator: "IsEqualTo", value: value });
}

//Predicates
//Ex: [{ "field": "VATGroupID", "operator": "contains","value": "1" }, { "field": "ABC", "operator": "contains", "value": "1" }]
function SetMultiPredicateForCombo(fieldName, Predicates) {
    var combobox = $("#" + fieldName + "").data("kendoComboBox");
    var objfilter = $.parseJSON(Predicates);
    if (!IsNull(combobox))  combobox.dataSource.filter(objfilter);
}

//codeBasePopup.SetMultiPredicateComplexForCombo("CashAcctID", "(AccountID.IndexOf(~0)==0||AccountID.IndexOf(~1)==0||AccountID.IndexOf(~2)==0)&&!AccountID.Equals(~3)&&Detail.Equals(~4)", "1|4|5|111|true");
function SetMultiPredicateComplexForCombo(fieldName, Predicates, values) {
    var combobox = $("#" + fieldName + "").data("kendoComboBox");
    if (!IsNull(combobox)) combobox.dataSource.filter({ field: Predicates, operator: "IsEqualTo", value: values });

}

//codeBasePopup.SetMultiPredicateComplexForCombo("CashAcctID", "(AccountID.IndexOf(~0)==0||AccountID.IndexOf(~1)==0||AccountID.IndexOf(~2)==0)&&!AccountID.Equals(~3)&&Detail.Equals(~4)", "1|4|5|111|true");
function SetMultiPredicateComplexForLVCombo(fieldName, Predicates, values) {
    var combobox = $("#" + fieldName + "").LVComboBox().data("LVComboBox");
    if (!IsNull(combobox)) combobox.filter({ field: Predicates, operator: "IsEqualTo", value: values });
}

function GridLoadData(gridViewName, url)
{
    var grid = $('#' + gridViewName).data("kendoGrid");
    grid.dataSource.transport.options.read.url = url;
    grid.dataSource.read();
}

function GridLoadDataByPredicate(gridViewName, Predicate,Value) {
    var grid = $('#' + gridViewName).data("kendoGrid");

    Predicate = Predicate.replaceAll("=", "_equals_");
    Predicate = Predicate.replaceAll("&&", "_and_");
    Predicate = encodeURI(Predicate);
    Value = encodeURI(Value);

    var url = $.ModifiedParaUrl(grid.dataSource.transport.options.read.url, "fieldcustomPredicate", Predicate);
    url = $.ModifiedParaUrl(url, "valuecustomPredicate", Value);

    grid.dataSource.transport.options.read.url = url;
    grid.dataSource.read();
}


//trên lưới con khi khi dùng tab edit thì không chọn được dòng
function FixGridTabEdit(o)
{
    setTimeout(function () {
        if (!IsNull(o) && !IsNull(o.current()))
            o.select(o.current().parent());
    }, 10);
    return true;
}

kendo.data.DataSource.prototype.AutoLoadData = true;

function RequestStart(e)
{
    if (e.sender.AutoLoadData == false) {
        e.preventDefault();
    }
}

function CheckPermission(type)
{
    if (permission == null || permission.length == 0) return false;
    for (var i = 0; i < permission.length; i++) {
        if (permission[i].FType == type)
            return permission[i].FIsActive;
    }
    return false;
}


function updateCell(gridViewName, columnName, rowIndex, model)
{
    setTimeout(function () {
        var gridview = $("#" + gridViewName).data("kendoGrid");
        var colIndex = -1;

        var col = null;
        for (var i = 0; i < gridview.columns.length; i++) {
            if (gridview.columns[i].field == columnName) {

                colIndex = i;
                col = gridview.columns[i];
                break;
            }
        }

        if (colIndex == -1) return;
        if (gridview.tbody.children().length < rowIndex) return;

        var row = gridview.tbody.children()[rowIndex];
        var cell = $(row).children()[colIndex];

        if (!cell) return;

        gridview._displayCell($(cell), col, model);
    }, 50);
}

function closeCell(gridViewName)
{
    var gridview = $("#" + gridViewName).data("kendoGrid");
    gridview.closeCell();
}

function editCell(gridViewName, columnName, next, rowIndex, modelselect) {
    setTimeout(function () {
        var gridview = $("#" + gridViewName).data("kendoGrid");
        var colIndex = -1;
        var col = null;
        for (var i = 0; i < gridview.columns.length; i++) {
            if (gridview.columns[i].field == columnName) {
                if (next)
                {
                    for (var j = i+1; j < gridview.columns.length; j++) {
                        if (gridview.columns[j].hidden!=true) {
                            colIndex = j;
                            col = gridview.columns[j];
                            break;
                        }
                    }
                }

                colIndex = i;

                col = gridview.columns[i];
                break;
            }
        }

        if (colIndex == -1) return;

        if (typeof rowIndex == "undefined" || rowIndex == null)
        {
            if (modelselect)
            {
                rowIndex = gridview.dataSource.data().indexOf(modelselect);
            }
            else
            {
                var model = GetCurrentRowEx(gridview);
                if (model)
                    rowIndex = gridview.dataSource.data().indexOf(model);
            }
            
        }

        if (typeof rowIndex == "undefined" || gridview.tbody.children().length < rowIndex) return;

        var row = gridview.tbody.children()[rowIndex];
        var cell = $(row).children()[colIndex];

        if (!cell) return;

        SelectRowByIndex(gridview, rowIndex);
        gridview.closeCell();
        gridview.editCell($(cell));
    }, 500);
}

function SetAgainGridFocus(gridViewName)
{
    var gridview = $("#" + gridViewName).data("kendoGrid");
    var current = gridview.current();
    if (current.length > 0) {
        var inp = current.find(".k-input");
        for (var i = 0; i < inp.length; i++) {
            if ($(inp).is(':visible')) {
                $(inp).focus();
            }
        }
    }
}

function RowCurrentIndex(gridViewName)
{
    var gridview = $("#" + gridViewName).data("kendoGrid");
    var current = GetCurrentRowEx(gridview);
    if (current)
    {
        return gridview.dataSource.data().indexOf(current);
    }
    else
    {
        return -1;
    }
}

var BridgeFunction = null;

function SetBridgeFunction(f)
{
    if (window.frameElement == null)
        BridgeFunction = f;
    else
        window.parent.BridgeFunction = f;
}

function CallBridgeFunction() {
    if (window.frameElement == null)
        return BridgeFunction();
    else
        return window.parent.BridgeFunction();
}


function CheckSingleUI() {
    if (window.frameElement == null) {
        if (typeof SingleUI != 'undefined')
            return SingleUI;
    }
    else
        if (typeof window.parent.SingleUI != 'undefined')
            return window.parent.SingleUI;

    return 0;
}

function LinkAdd(name, functionID,fieldvalue)
{
    var data = PostServer(GetBaseUrl() + 'Shared/GetFunction?functionID=' + functionID);
    if (!IsNull(data))
    {
        var value= GetCombobox(name);
        var url = GetBaseUrl() + data.Url + "/Add";
        if (data.Width == 0)
        {
            ShowWindowCallback(url, 0, 0, 'Add ' + data.CustomName, function () { LinkRefresh(name, functionID, fieldvalue); });
        }
        else
        {
            ShowWindowCallback(url, data.Width, data.Height, 'Add ' + data.CustomName, function () { LinkRefresh(name, functionID, fieldvalue); });
        }
    }
}

function LinkRefresh(name, functionID, fieldvalue) {
    if ($("#" + name).length > 0)
    {
        var combobox = $("#" + name + "").data("kendoComboBox");
        combobox.dataSource.read();
        combobox.refresh();
    }
}


function LVLinkAdd(name, functionID, fieldvalue) {
    var data = PostServer(GetBaseUrl() + 'Shared/GetFunction?functionID=' + functionID);
    if (!IsNull(data)) {
        var url = GetBaseUrl() + data.Url + "/Add";
        if (data.Width == 0) {
            ShowWindowCallback(url, 0, 0, 'Add ' + data.CustomName, function () { LVLinkRefresh(name, functionID, fieldvalue); });
        }
        else {
            ShowWindowCallback(url, data.Width, data.Height, 'Add ' + data.CustomName, function () { LVLinkRefresh(name, functionID, fieldvalue); });
        }
    }
}

function LVLinkRefresh(name, functionID, fieldvalue) {
    if ($("#" + name).length > 0) {
        var combobox = $("#" + fieldName + "").LVComboBox().data("LVComboBox");
        combobox.ReadData(0);
    }
}

function HideToolbarWindowOfMetro(hide)
{
    if ($("#windowsopen").length > 0) {
        if(hide)
            $("#windowsopen").hide();
        else
            $("#windowsopen").show();
    }

    if ($("#navbar").length > 0) {
        if (hide)
            $("#navbar").hide();
        else
            $("#navbar").show();
    }
}

function EnableMenu(menuName,menuItem,enable) {
    var menu = document.body.querySelector('#morelayout');
    if (!IsNullOrEmty(menu)) {
        var command = menu.winControl.getCommandById(menuItem);
        command.disabled = !enable;
        
    }
}

function RefreshExcel(src)
{
    src = $.getStringVar(src, "src");
    return PostServer(GetBaseUrl() + 'Shared/RefreshExcel?src=' + src);
}

function ChooseColor(gridName, FieldName)
{
    
    if(PreShowColorChoose != 'undefined')
        if(PreShowColorChoose() == false)  return;

    if ($("#ChooseColorDiv").length == 0) {
        $("<div id='ChooseColorDiv' style='position: absolute;top:50%;left:0px;width:100%;height:0px;overflow: visible;background:red;'><div style='width:252px;height:260px;margin-left:-125px;position:absolute;top:-100px;left:50%;background:#ccc;'><div id='ColorPi'/><button style=\"margin-left:20px\" type='Button' onclick='applyChooseColor(\"" + gridName + "\",\"" + FieldName + "\")'>Choose</button><button style=\"margin-left:20px\" type='Button' onclick='closeChooseColor()'>Close</button></div></div>").appendTo("body");


        $("#ColorPi").kendoFlatColorPicker({
            preview: false,
            value: "#000"
        });
    }
    else {
        $("#ChooseColorDiv").show();
    }
    
}

function closeChooseColor()
{
    $("#ChooseColorDiv").hide();
}


function applyChooseColor(gridName, FieldName) {

    var data = GetCurrentRow(gridName);
    var p = $("#ColorPi").data("kendoFlatColorPicker");
    if (data != null) {
        data.set(FieldName, p.value());
    }

    $("#ChooseColorDiv").hide();
}

function CheckFromDateToDate(FromDate, ToDate, InstallDate)
{
    //var dt = InstallDate.split(/\-|\s/);
    //dat = new Date(dt.slice(0, 3).reverse().join('/') + ' ' + dt[3]);

    //var intsDate = new Date('31/12/2010');
    //if (FromDate < dat)
    //{
    //    ShowMessage('AccNet E', 'From_Date_Must_Larger_Than_Install_Date', 'From Date Must Larger Than Install Date.', null, null, 'OK');
    //    return true;
    //}

    if (FromDate > ToDate)
    {
        ShowMessage('AccNet E', 'From_Date_Must_Less_Than_Or_Equal_To_Date', 'From Date Must Less Than Or Equal To Date.', null, null, 'OK');
        return true;
    }    
}

function Round(value, decimals) {
    return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}

function UpdateLayoutGrid(gridViewName ){
    var gridView = $('#' + gridViewName ).data("kendoGrid");
    //gridView._updateTablesWidth(); 
    //gridView._applyLockedContainersWidth();
    //gridView._syncLockedContentHeight();
}

function CheckRunOnWinStore()
{
    // We have a couple of checks to make sure the 'external' 
    // object and 'notify' method exist before we try using them 
    // because our project is a web application and might not be 
    // running in a WebView control (the checks prevent 
    // JavaScript errors if the method doesn't exist) 
    if (window.frameElement == null) {
        if ((typeof (window.external) !== "undefined") && (typeof (window.external.notify) !== "undefined")) {
            return true;
        }
    }
    else {
        if ((typeof (window.parent.external) !== "undefined") && (typeof (window.parent.external.notify) !== "undefined")) {
            return true;
        }
    }
    
    return false;
}

function WinRT_ShowMessage(message,button,callback)
{
    var msg = new Windows.UI.Popups.MessageDialog(message);

    if (typeof button != "undefined" && button.toLowerCase() == 'yesno')
    {
        msg.commands.append(new Windows.UI.Popups.UICommand("Yes", null,"YES"));
        msg.commands.append(new Windows.UI.Popups.UICommand("No", null,"NO"));
    }
    else
        msg.commands.append(new Windows.UI.Popups.UICommand("OK", null));
    msg.showAsync().done(function (command) {
        if(!IsNullOrEmty(callback))
        {
            callback(command.id);
        }
    });
}

function WinRT_GetFormatNumber(format,mask)
{
    if(typeof(format) != "undefined")
        format = format.toLowerCase();
    
    if(IsNullOrEmty(mask))
        mask = "#";

    var adsetup = WinRT_AD_Setup();
    var dec = 0;
    if(format=="s")
        dec = adsetup.SourceAmtDec;
    else if (format == "b")
        dec = adsetup.BaseAmtDec;
    else if (format == "p")
        dec = adsetup.PercentDec;
    else if (format == "r")
        dec = adsetup.RateExchDec;
    else if (format == "q")
        dec = adsetup.QuantityDec;
    else if (format == "u")
        dec = adsetup.UnitCostDec;

    var stringformat = mask + "," + mask + mask + mask;

    if (dec >= 1)
        stringformat = stringformat + ".";
    if (dec >= 2)
        stringformat = stringformat + mask;
    if (dec >= 3)
        stringformat = stringformat + mask;
    if (dec >= 4)
        stringformat = stringformat + mask;
    if (dec >= 5)
        stringformat = stringformat + mask;
    if (dec >= 6)
        stringformat = stringformat + mask;
    if (dec >= 7)
        stringformat = stringformat + mask;
    if (dec >= 8)
        stringformat = stringformat + mask;

    if (dec >= 1)
        stringformat = stringformat + "0";

    return stringformat + ";(" + stringformat + "); ";
}
function WinRT_AD_Setup()
{
    var lib = new libAccNetC.lib();
    return $.parseJSON(lib.ad_Setup);
}

function WinRT_ShowReport(url)
{
    var nav = document.body.querySelector('#createNavBar');
    if (!IsNullOrEmty(nav))
        nav.winControl.hide();

    var appbar = document.body.querySelector('#commandsAppBar');
    if (!IsNullOrEmty(appbar))
        appbar.winControl.hide();

    ShowBusy('busy');

    var httpClient = new Windows.Web.Http.HttpClient();
    headers = httpClient.defaultRequestHeaders;
    headers.append("winrt", appConfig.session);
    
    var localUri = new Windows.Foundation.Uri(url);
    var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.get, localUri);

    var httpPromise = httpClient.sendRequestAsync(
        request,
        Windows.Web.Http.HttpCompletionOption.responseHeadersRead).then(function (response) {
            readBuffer = Windows.Security.Cryptography.CryptographicBuffer.createFromByteArray(new Array(response.content.headers.contentLength));
            return response.content.readAsInputStreamAsync();
        }).then(function (responseStream) {
            if (readBuffer==null || readBuffer.length == 0) {
                WinRT_ShowMessage("Report No Data");
                HideBusy('busy');
                return;
            }
            responseStream.readAsync(readBuffer, readBuffer.capacity, Windows.Storage.Streams.InputStreamOptions.none).then(function (buffer) {
                // Continue reading until the response is complete.
                Windows.Storage.ApplicationData.current.temporaryFolder.createFileAsync(GenarateIDWindow() + ".pdf", Windows.Storage.CreationCollisionOption.replaceExisting).done(
                    function (file) {
                        Windows.Storage.FileIO.writeBufferAsync(file, buffer).done(
                         function () {
                             Windows.System.Launcher.launchFileAsync(file).done(
                                function (success) {
                                    // anything you want to do after default program launched        });
                                });
                             HideBusy('busy');
                         },
                         function (error) {
                             WinRT_ShowMessage(error);
                             HideBusy('busy');
                         });
                                            
                    },
                    function (error) {
                        WinRT_ShowMessage(error);
                        HideBusy('busy');
                    });


            });
                        
            
        });

    httpPromise.done(function () {
    });


}

function GoBack()
{
    window.history.back();
}

function GoPage(page)
{
    var uri = Windows.Foundation.Uri("ms-appx:///" + page);  
    Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).then(function (e) {
        if(window.frameElement == null)
            document.location = page;
        else
            window.parent.document.location = page;
    }, function (e) {
        WinRT_ShowMessage("This function is processing and will have in next version.");
    });

}

function GoToSessionPage(page)
{
    document.location = page;
}
var idWindow = "";


//Goi tu form pupup
function closeWindow(_isRefreshData, key, idWindow) {
    CloseWin();
}

function CloseWin(e) {
    if (window.frameElement == null)
        GoBack();
    else
    {
        var flyout = window.parent.document.getElementById("confirmFlyout");
        if(flyout!=null && !IsNullOrEmty(flyout.winControl.callback))
        {
            flyout.winControl.callback(e);
            flyout.winControl.hide();
        }
    }
}


function ListFilesInFolder(folder,level, lib)
{
    folder.getFoldersAsync().then(function (fs) {
        var childlevel = level + 1;
        for (var f = 0; f < fs.length;f++) {
            ListFilesInFolder(fs[f], childlevel,lib);
        }

        if (folder.path.indexOf("pages")>0)
        {
            folder.getFilesAsync().then(function (files) {
                for (var f = 0; f < files.length; f++) {
                    if (files[f].fileType == ".html") {
                        var begin = files[f].path.lastIndexOf("\\pages");
                        lib.addPage(files[f].path.substr(begin, files[f].path.length - begin));
                    }
                }
            
            });
        }
    });
}

function selectfunction(item){
    if (IsNullOrEmty(item.Url)) {
        WinRT_ShowMessage("Can not find this page");
        return;
    }

    GoPage("/pages/" + item.Module + "/" + item.Url + "/index.html");
}

$(window).resize(function () {
    var notsupport = $("#notsupport");
    
    if (notsupport.length == 0)
    {
        notsupport = $("<div id=\"notsupport\" style=\"padding-left:50px;display:none;position:fixed;background:url('/images/bgHubPage.png');background-size:cover;width:100%;height:100%;z-index:100000;top:0px;left:0px;\" />");

        notsupport[0].innerHTML = "<span style=\"color:black;margin-left:50px;margin-top:50px;\"><h2>Application can not support this display<h2></span>";

        $('body').append(notsupport[0]);
    }

    if($(window).width() < $(window).height())
    {
        notsupport.show();
    }
    else
    {
        notsupport.hide();
    }
    
})


// choose where the file will be stored:
var fileDestination = Windows.Storage.ApplicationData.current.localFolder;

var logger = new WinJS.Promise(function (complete) {
    var logfilename = new Date().toISOString().replace(/[:-]/g, "");
    logfilename = "lvlog-" + logfilename + ".log";
    fileDestination.createFileAsync(logfilename,
        Windows.Storage.CreationCollisionOption.generateUniqueName)
            .done(function (file) {
                complete(file);
            });
});

function lvlog(message, tag, type) {
    //logger.then(function (file) {
    //    var m = WinJS.Utilities.formatLog(message, tag, type);
    //    Windows.Storage.FileIO.appendTextAsync(file, m).done();
    //});
};

WinJS.Application.onsettings = function (e) {
    e.detail.e.request.applicationCommands.append(new Windows.UI.ApplicationSettings.SettingsCommand('privacypolicy', 'Privacy policy ', function () {
        Windows.System.Launcher.launchUriAsync(new Windows.Foundation.Uri('http://accnet.cloud.com.vn/appaccnetc/help/privacypolicy.html'));
    }));
};

//WinJS.Application.onsettings = function (e) {
//    e.detail.applicationcommands = { "help": { title: "Help", href: "http://www.vietgle.vn/sachbaovn/help/en/privacy-policy.htm" } };
//    WinJS.UI.SettingsFlyout.populateSettings(e);
//};
WinJS.Application.start();